package com.ds.robot.assistant.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.region.Region;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.util.Comparator;
import java.util.List;

/**
 * 作用：临时用一下
 * 对象存储 列出对象-SDK 文档-文档中心-腾讯云
 * https://cloud.tencent.com/document/product/436/65938
 *
 * @author WeiShaoying
 * 
 */
@Slf4j
@SuppressWarnings("all")
public class CosVideoService {

    // 开发者拥有的项目身份识别 ID
    private static final String secretId = "AKIDqVw85oIchX6PRJyNWP1NjBYhaDbkcDdn";
    //开发者拥有的项目身份密钥
    private static final String secretKey = "0jBOM4WlmZ8UcU7WijX6SZS7XllX6SaT";

    private static final String REGION = "ap-beijing";
    private static final String CDN_HOST = "https://shangcheng.renruikeji.cn";
    private static final String bucketName = "shangxueyuan-1301970825";
    private static final String prefix = "video/";

    // 创建 COSClient 实例，这个实例用来后续调用请求
    private static COSClient createCOSClient() {
        // 设置用户身份信息
        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        // String secretId = System.getenv("secretId");//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        // String secretKey = System.getenv("secretKey");//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        // ClientConfig 中包含了后续请求 COS 的客户端设置：
        ClientConfig clientConfig = new ClientConfig();

        // 设置 bucket 的地域
        // COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224
        clientConfig.setRegion(new Region(REGION));

        // 以下的设置，是可选的：

        // 设置 socket 读取超时，默认 30s
        // clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时，默认 30s
        // clientConfig.setConnectionTimeout(30*1000);

        // 如果需要的话，设置 http 代理，ip 以及 port
        // clientConfig.setHttpProxyIp("httpProxyIp");
        // clientConfig.setHttpProxyPort(80);

        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

    public static void listBigFile() {
        // // 初始化COS客户端代码...
        // // 1 传入获取到的临时密钥 (tmpSecretId, tmpSecretKey, sessionToken)
        // // String tmpSecretId = "SECRETID";
        // // String tmpSecretKey = "SECRETKEY";
        // String sessionToken = "TOKEN";
        //
        // BasicSessionCredentials cred = new BasicSessionCredentials(secretId, secretKey, sessionToken);
        // // 2 设置 bucket 的地域
        // // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分
        //
        // Region region = new Region("ap-beijing"); //COS_REGION 参数：配置成存储桶 bucket 的实际地域，例如 ap-beijing，更多 COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端
        // COSClient cosClient = new COSClient(cred, clientConfig);
        COSClient cosClient = createCOSClient();
        List<CosFile> fileList = Lists.newArrayList();

        // Set<String> videoExtensions = new HashSet<>();
        // videoExtensions.add("mp4");
        // videoExtensions.add("avi");
        // videoExtensions.add("mov");

        // 列举桶中的文件
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(bucketName);
        listObjectsRequest.setPrefix(prefix);

        ObjectListing objectListing;
        do {
            objectListing = cosClient.listObjects(listObjectsRequest);
            // for (COSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            //     String key = objectSummary.getKey();
            //     String extension = key.substring(key.lastIndexOf(".") + 1);
            //     if (videoExtensions.contains(extension)) {
            //         // 打印视频文件名和大小
            //         System.out.println("视频文件名: " + key + ", 大小: " + objectSummary.getSize() + " bytes");
            //     }
            // }

            List<COSObjectSummary> summaryList = objectListing.getObjectSummaries();
            for (COSObjectSummary summary : summaryList) {
                String key = summary.getKey();
                String extension = key.substring(key.lastIndexOf(".") + 1);
                if (!extension.equals("mp4")) {
                    continue;
                }
                System.out.println(JSON.toJSONString(summary));
                String etag = summary.getETag();
                // 存储类型
                String storageClasses = summary.getStorageClass();

                long size = summary.getSize();
                // 将字节转换成MB,GB
                BigDecimal fileSizeMb = new BigDecimal(size).divide(new BigDecimal(1024 * 1024), 2, RoundingMode.HALF_UP);
                BigDecimal fileSizeGb = new BigDecimal(size).divide(new BigDecimal(1024 * 1024 * 1024), 2, RoundingMode.HALF_UP);

                if (fileSizeMb.compareTo(new BigDecimal(300)) > 0) {
                    URL fileUrl = cosClient.getObjectUrl(bucketName, key);
                    String url = CDN_HOST + fileUrl.getPath();
                    // String fileName = url.substring(url.lastIndexOf("/") + 1);
                    CosFile file = new CosFile(key, url, size, fileSizeMb, fileSizeGb);
                    fileList.add(file);
                }
            }
            // 标记下一次开始的位置
            String nextMarker = objectListing.getNextMarker();
            listObjectsRequest.setMarker(nextMarker);

        } while (objectListing.isTruncated());

        log.info("============================= 大文件数量={} ============================= ", fileList.size());

        // Stream按照fileSize 降序排序
        fileList.sort(Comparator.comparingLong(CosFile::getFileSize).reversed());
        fileList.forEach(file -> System.out.println(JSON.toJSONString(file)));
        System.out.println("\n\n\n");
        String str = "";
        for (CosFile cosFile : fileList) {
            str += "'" + cosFile.getFileUrl() + "',";
        }
        str = str.substring(0, str.length() - 1);
        System.out.println(str);

        // 关闭客户端
        cosClient.shutdown();
    }

    public static void main(String[] args) {
        listBigFile();
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class CosFile {

        private String fileName;

        private String fileUrl;

        private Long fileSize;

        private BigDecimal fileSizeMb;

        private BigDecimal fileSizeGb;

    }

}
